<?php


namespace app\api\controller;

use app\common\model\InvoicingLog;
use app\common\controller\Api;

use app\common\model\Message;
use think\Db;
use Yansongda\Pay\Pay as ePay;
use Yansongda\Pay\Log;
class Pay extends Api
{
    protected $noNeedLogin = ['*'];//空代表都需要验证
    protected $noNeedRight = ['*'];
    // 支付宝配置文件
    protected $configAli = [
        'app_id'=>2021002103642579,

        'notify_url'=>'',

        'return_url'=>'http://yansongda.cn/return.php',

        'ali_public_key'=>'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgqwo1xvi2P2xXKSI4RXQSHGRPb0mpAVcMXMgXvHx683JzgmkW0mLJISoNil0XehqIks3RjGkN0giRjo8RO74nuAK9g5IlQbHlYx5H2K0bfATfrMEoUJEwbbhfX/v04Ls7+bw07ZXb2mmpwLS0HbOFdYz+JlYuOWmcJ3ytoldD28V+z9EeGBHksEmwbNqzWuwZ1+84B6W03s0Xv5xWoP5M3t6wJMACPg7CLSUYkAM5GkEF81/UceZldMtQekXhDZDq9Wy2sz+vWYeefWGKl0AQ55R1gZT61iN6yTspa/ToLqHN19SiRScKxxASorM/ZVebscPLIe/20X1g81SrDVmFwIDAQAB',

        'private_key'=>'MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCBRPGG5GAq3kaQFsuF+zeMUiuDJamMCXJgdEtFwmCBAQmRu/6uTiuK5rMAMgBYwvrR7HEYR/lEbcJx37OrVLA+qlNQKOknBC02QLJOplKuFK6eb9tpth+s/z1kfCLmPQ7iG1OtdrjhCDRaqSeMRyD1l2fgGZlttr4vdMcVvCLj6HZZmpr2GyJpTEAqwvV0+admLl5jX4mrK5vNm3NtfODjxiJ24ABC+M1TDt1Pg3yEbgyhnrjCsp/eo7pa8jozxJTfHK2meQ/yQ1UJg8/sE5KBHqb8GnfTJZ+UNJazOmK+cTJPMhkb4Cc5UByblMLngeRV1/CagC6SKBVdjNrWYTFnAgMBAAECggEAEgW7qrPSWIeuzM3wyBgzMW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gs7TS2GxIp6DiNH3A7JZpEaP71+tKX0XqMaH9DeMp/ltPd8NOu2aJXPyVjplilh8WZsh7/Mvlsf/m0Kf8iwtGgGwS0+9v0CWl9o0j1IYu1mWRYPpm8hN0UD2BH5PDI9/2xfWFw==',

        'log' => [ // optional
            'file' => './logs/alipay.log',
            'level' => 'info', // 建议生产环境等级调整为 info，开发环境为 debug
            'type' => 'single', // optional, 可选 daily.
            'max_file' => 30, // optional, 当 type 为 daily 时有效，默认 30 天
        ],
        'http' => [ // optional
            'timeout' => 5.0,
            'connect_timeout' => 5.0,
            // 更多配置项请参考 [Guzzle](https://guzzle-cn.readthedocs.io/zh_CN/latest/request-options.html)
        ],
        'mode' => 'normal', // optional,设置此参数，将进入沙箱模式
    ];
    protected $weChatConfig = [
        'appid' => 'wxe44dbdb4a907b8f6', // APP APPID
//        'app_id' => 'wx574ceb4fd62bfe95', // 公众号 APPID
        'app_id' => 'wxa6786c015595e325', // 网站应用
        'miniapp_id' => 'wxbfb9eb2e2901d588', // 小程序 APPID
        'mch_id' => '1604428204',//商户id
        'key' => '1af26b1c47bcb1c9800d2c0ac8f8a025',//商户秘钥
        'miniapp_key' => '1af26b1c47bcb1c9800d2c0ac8f8a025',//小程序秘钥
        'app_key' => 'bc13d009c11439110ba33f8f282a504d',//网站应用 秘钥
        'notify_url' => '',
        'cert_client' => './cert/apiclient_cert.pem', // optional，退款等情况时用到
        'cert_key' => './cert/apiclient_key.pem',// optional，退款等情况时用到
        'log' => [ // optional
            'file' => './logs/wechat.log',
            'level' => 'info', // 建议生产环境等级调整为 info，开发环境为 debug
            'type' => 'single', // optional, 可选 daily.
            'max_file' => 30, // optional, 当 type 为 daily 时有效，默认 30 天
        ],
        'http' => [ // optional
            'timeout' => 10.0,
            'connect_timeout' => 10.0,
            // 更多配置项请参考 [Guzzle](https://guzzle-cn.readthedocs.io/zh_CN/latest/request-options.html)
        ],
        'mode' => 'normal', // optional, dev/hk;当为 `hk` 时，为香港 gateway。
    ];
    protected $weChatWebdocConfig = [];

//    //微信支付
//    protected $weChatConfig = [
//        'appid' => 'wx574ceb4fd62bfe95', // APP APPID
//        'app_id' => 'wx574ceb4fd62bfe95', // 公众号 APPID
//        //  'miniapp_id' => 'wxb3fxxxxxxxxxxx', // 小程序 APPID
//        'mch_id' => '1601622273',
//        'key' => 'LHS6UcbEUzuaVlO4mcggjYoLhrbWgvur',
//        'notify_url' => '',
//        'cert_client' => './cert/apiclient_cert.pem', // optional，退款等情况时用到
//        'cert_key' => './cert/apiclient_key.pem',// optional，退款等情况时用到
//        'log' => [ // optional
//            'file' => './logs/wechat.log',
//            'level' => 'debug', // 建议生产环境等级调整为 info，开发环境为 debug
//            'type' => 'single', // optional, 可选 daily.
//            'max_file' => 30, // optional, 当 type 为 daily 时有效，默认 30 天
//        ],
//        'http' => [ // optional
//            'timeout' => 10.0,
//            'connect_timeout' => 10.0,
//            // 更多配置项请参考 [Guzzle](https://guzzle-cn.readthedocs.io/zh_CN/latest/request-options.html)
//        ],
//        'mode' => 'normal', // optional, dev/hk;当为 `hk` 时，为香港 gateway。
//    ];


    public function index()
    {

        $order = [
            'out_trade_no' => time(),
            'body' => '',
            'total_fee' => 1,
        ];
        $pay = ePay::wechat($this->weChatConfig)->app($order);
      //  $alipay = ePay::alipay($this->configAli)->app($order);

        return $pay->send();// laravel 框架中请直接 `return $alipay`
    }
    /**
     * 统一下单接口
     * $pay_mode1微信2支付宝
     * $amount支付金额
     * $order_type 1用户订单2商户订单
     * $order_sn用户订单号
     * $notify_url 回调地址
     * $body 购买提示语
     * $extra 额外参数
     */
    public function pay($pay_mode, $price, $order_sn,$notify_url,$body,$extra=null) {
//        $price = 0.01;
        if ($pay_mode == 1) {
            $result = $this->wechatindex($order_sn, $price,$notify_url.'1',$body,$extra);
//            dd($result);
        } else {
            $result = $this->aliIndex($order_sn, $price,$notify_url,$body,$extra);
        }
        return $result;
    }
    //小程序支付
    public function payMniapp($price, $order_sn,$notify_url,$body,$extra=[]) {
//        $price = 0.01;

        $result = $this->wechatindexMniapp($order_sn, $price,$notify_url.'1',$body,$extra);

        return $result;
    }
    /**
     * 统一下单接口
     * $pay_mode1微信2支付宝
     * $amount支付金额
     * $order_type 1用户订单2商户订单
     * $order_sn用户订单号
     * $notify_url 回调地址
     * $body 购买提示语
     * $extra 额外参数
     */
    public function webpay($pay_mode, $price, $order_sn,$notify_url,$body,$extra=null) {

        if ($pay_mode == 1) {
            $result = $this->webwechatindex($order_sn, $price,$notify_url.'1',$body,$extra);
        } else {
            $result = $this->webaliIndex($order_sn, $price,$notify_url,$body,$extra);
        }
        return $result;
    }



    /**
     * 微信支付-app
     * @param $order_sn
     * @param $price
     */
    public function wechatindex($order_sn, $price,$notify_url,$body,$extra='') {
//        $price = 0.01;
        $all_price = $price * 100;
//        //测试账号，支付0.01
//        $user_id = $this->auth->id;
//        $rs = cs_user();
//        if(in_array($user_id,$rs)){
//            $all_price=0.01;
//        }
        $order = [
            'out_trade_no' => $order_sn,
            'body' => $body,
            'total_fee' => $all_price,
        ];

        $this->weChatdocConfig = config('wetch');
        $this->weChatdocConfig['notify_url']=$notify_url;

        $pay = ePay::wechat($this->weChatdocConfig)->app($order);
        $cc = $pay->getContent();
        $aa = json_decode($cc, true);
        $this->success('success', ['info'=>$aa,'order_sn'=>$order_sn,'data'=>$extra]);

    }
    /**
     * 微信支付-小程序
     * @param $order_sn
     * @param $price
     */
    public function wechatindexMniapp($order_sn, $price,$notify_url,$body,$extra=[]) {

        $all_price = $price * 100;
        //测试账号，支付0.01
//        $user_id = $this->auth->id;
//        $rs = cs_user();
//        if(in_array($user_id,$rs)){
//            $all_price=0.01;
//        }

        $this->weChatdocConfig = config('wetch');
        $this->weChatdocConfig['notify_url']=$notify_url;
//        $this->weChatdocConfig['key']= config('wetch.miniapp_key');

        $order = [
            'out_trade_no' => $order_sn,
            'body' => $body,
            'total_fee' => $all_price,
            'openid' => $extra['openid'],
        ];
//        ePay::wechat($this->weChatdocConfig)
//        $result = $wechat->miniapp($order);
        $pay = ePay::wechat($this->weChatdocConfig)->miniapp($order);


//        $cc = $pay->getContent();
        $aa = json_decode($pay, true);
        $this->success('success', ['info'=>$aa,'order_sn'=>$order_sn,'data'=>$extra]);

    }

    /**
     * 微信支付-pc 支付
     * @param $order_sn
     * @param $price
     */
    public function webwechatindex($order_sn, $price,$notify_url,$body,$extra='') {
//        $price = 0.01;
        $all_price = $price * 100;
        $order = [
            'out_trade_no' => $order_sn,
            'body' => $body,
            'total_fee'      => $all_price,
        ];
        $this->weChatWebdocConfig = config('wetch');

        $this->weChatWebdocConfig['app_id']=$this->weChatWebdocConfig['appid'];
        $this->weChatWebdocConfig['notify_url']=$notify_url;

        unset($this->weChatConfig['app_key']);
        unset($this->weChatConfig['miniapp_key']);
        $pay = ePay::wechat($this->weChatWebdocConfig)->scan($order);
//        dd($pay);
        $qr  = qrcode($pay->code_url,$order_sn);
        $this->success('success', ['info'=>$qr,'order_sn'=>$order_sn,'data'=>$extra]);

    }

    /**
     * 支付宝支付-pc 支付
     * @throws \Yansongda\Pay\Exceptions\InvalidConfigException
     * @throws \Yansongda\Pay\Exceptions\InvalidSignException
     */
    public function webaliIndex($order_sn, $all_price,$notify_url,$body,$extra='') {
//        $all_price = 0.01;
        $order = [
            'out_trade_no' => $order_sn,
            'total_amount' => $all_price,
            'subject' => $body,
        ];
        $this->configAli = config('alipay');
        $this->configAli['notify_url']=$notify_url;
        $alipay = ePay::alipay($this->configAli)->web($order)->send(); // laravel 框架中请直接 return $alipay->web($order)
        $cc = $alipay->getContent();
        $this->success('success', ['info'=>$cc,'order_sn'=>$order_sn,'data'=>$extra]);

    }

    /**
     * 支付宝支付-app
     * @throws \Yansongda\Pay\Exceptions\InvalidConfigException
     * @throws \Yansongda\Pay\Exceptions\InvalidSignException
     */
    public function aliIndex($order_sn, $all_price,$notify_url,$body,$extra='') {
        $user_id = $this->auth->id;
        //测试账号，支付0.01
//        $rs = cs_user();
//        if(in_array($user_id,$rs)){
//            $all_price=0.01;
//        }
        $order = [
            'out_trade_no' => $order_sn,
            'total_amount' => $all_price,
            'subject' => $body,
        ];
        $this->configAli=config('alipay');
        $this->configAli['notify_url']=$notify_url;
        $alipay = ePay::alipay(  $this->configAli)->app($order);
        $cc = $alipay->getContent();
        $aa['info'] = $cc;
        $this->success('success', ['info'=>$aa,'order_sn'=>$order_sn,'data'=>$extra]);

    }


    /**
     * @return \Symfony\Component\HttpFoundation\Response
     * 支付宝 订单支付回调
     */
    public function courseNotify()
    {
        $request=input();
        $alipay = ePay::alipay($this->configAli);
        try{
//            $data = $alipay->verify($request); // 是的，验签就这么简单！
            $data = $request; // 是的，验签就这么简单！
            // 请自行对 trade_status 进行判断及其它逻辑进行判断，在支付宝的业务通知中，只有交易通知状态为 TRADE_SUCCESS 或 TRADE_FINISHED 时，支付宝才会认定为买家付款成功。
            // 1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号；
            // 2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额）；
            // 3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）；
            // 4、验证app_id是否为该商户本身。
            // 5、其它业务逻辑情况
            $model=new \app\common\model\Order();
            $order_sn=$data['out_trade_no'];
            $trade_status=$data['trade_status'];

            $info=$model->where('order_sn','=',$order_sn)->find();
            if(empty($info)){
                $info=$model->where('order_sn_end','=',$order_sn)->find();
            }

            if ($trade_status=='TRADE_SUCCESS'){

                if(!empty($info)){
                    if($info['status']>1  ){
                        return $alipay->success()->send();
                    }
                    //是否为定金支付
                    if($info['earnest']>0  ){
                        if(!$info->earnesttime){
                            $info->earnesttime=time();
                        }else if(!$info->end_pricetime){
                            $info->end_pricetime=time();
                            $info->paytime=time();
                            $info->status=2;
                        }
                    }else{
                        $info->paytime=time();
                        $info->status=2;
                    }
                    $info->mode=2;
                    $info->save();
                    Message::getOrderAdd($info);

                }
            }

        //    Log::debug('Alipay notify', $data->all());
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // $e->getMessage();
            // 回滚事务
            Db::rollback();
        }

        return $alipay->success()->send();// laravel 框架中请直接 `return $alipay->success()`
//        return true;// laravel 框架中请直接 `return $alipay->success()`
    }
    /**
     * @return \Symfony\Component\HttpFoundation\Response
     * 微信 订单支付回调
     */
    public function courseNotify1()
    {

        $alipay = ePay::wechat($this->weChatConfig);
        //获取返回的xml
        $testxml = file_get_contents("php://input");
        //将xml转化为json格式
        $jsonxml = json_encode(simplexml_load_string($testxml, 'SimpleXMLElement', LIBXML_NOCDATA));
        //转成数组
        $request = json_decode($jsonxml, true);
        try{
//            $data = $alipay->verify($request); // 是的，验签就这么简单！
            $data = $request; // 是的，验签就这么简单！
            // 请自行对 trade_status 进行判断及其它逻辑进行判断，在支付宝的业务通知中，只有交易通知状态为 TRADE_SUCCESS 或 TRADE_FINISHED 时，支付宝才会认定为买家付款成功。
            // 1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号；
            // 2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额）；
            // 3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）；
            // 4、验证app_id是否为该商户本身。
            // 5、其它业务逻辑情况
            $model=new \app\common\model\Order();
            $order_sn=$data['out_trade_no'];
            $trade_status=$data['result_code'];

            $info=$model->where('order_sn','=',$order_sn)->find();
            if(empty($info)){
                $info=$model->where('order_sn_end','=',$order_sn)->find();
            }



            if ($trade_status=='SUCCESS'){
//                $info=$model->where('order_sn','=',$order_sn)->find();
//                if($info['status']>1 || $info['checking_status']>=1 ){
//                    return $alipay->success()->send();
//                }
//                if (!empty($info)){
//                    //是否为定金支付
//                    if($info['earnest']>0  ){
//                        if(!$info->earnesttime){
//                            $info->earnesttime=time();
//                        }else if(!$info->end_pricetime){
//                            $info->end_pricetime=time();
//                        }
//
//                    }
//                    $info->paytime=time();
//                    $info->status=2;
//                    $info->save();
//                }



                if(!empty($info)){
                    if($info['status']>1  ){
                        return $alipay->success()->send();
                    }
                    //是否为定金支付
                    if($info['earnest']>0  ){
                        if(!$info->earnesttime){
                            $info->earnesttime=time();
                        }else if(!$info->end_pricetime){
                            $info->end_pricetime=time();
                            $info->paytime=time();
                            $info->status=2;
                        }
                    }else{
                        $info->paytime=time();
                        $info->status=2;
                    }

                    $info->mode=1;
                    $info->save();
                    Message::getOrderAdd($info);
                }

            }

        //    Log::debug('Alipay notify', $data->all());
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // $e->getMessage();
            // 回滚事务
            Db::rollback();
        }
        return $alipay->success()->send();// laravel 框架中请直接 `return $alipay->success()`
    }



    /**
     * 退款
     * $order_sn订单号 $money金额  $mode 1微信 2支付宝
     * */
    public function refund($order_sn,$money,$mode=2){
        if($mode==1){
//            $this->weChatConfig= config('wetch');

            $money=$money*100;
            $alipay = ePay::wechat($this->weChatConfig);
//            dd( $alipay);
            $order = [
                'out_trade_no' => $order_sn,
                'out_refund_no' => time(),
                'total_fee' => $money,
                'refund_fee' => $money,
                'refund_desc' => '退款',
            ];
//            dd($order);
        }else{
            $this->configAli=config('alipay');
            $alipay = ePay::alipay($this->configAli);
            $order = [
                'out_trade_no' => $order_sn,
                'refund_amount' => $money,
            ];
        }
//
//        $result = $alipay->refund($order);
//        dd($result);
        try{
            $result = $alipay->refund($order);
            dd($result);
        } catch (\Exception $e) {
             $e->getMessage();
        }
    }
//
//    public function sda(){
//        $order = [
//            'out_trade_no' => '1514027114',
//        ];
//        $result = $wechat->find($order, 'refund');
//    }

}